<template>
  <el-container>
    <BomTree style="margin-top: 16px" @on-choose-region="filetrStation" />
    <el-main>
      <div class="default-main ba-table-box">
        <el-alert
          class="ba-table-alert"
          v-if="baTable.table.remark"
          :title="baTable.table.remark"
          type="info"
          show-icon
        />
        <!-- 表格顶部菜单 -->
        <TableHeader
          :buttons="[
            'refresh',
            'add',
            'edit',
            'remove',
            'comSearch',
            'columnDisplay',
          ]"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 表单 -->
        <PopupForm v-if="baTable.form.operate ? true : false" ref="formRef" />
      </div>
    </el-main>
  </el-container>
</template>
<script setup lang="ts">
import { ref, provide, onMounted, nextTick } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff, getDictData } from "@/utils/common"; // 导入表格api方法生成器
import { sysMUser } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import PopupForm from "./popupForm.vue";
import { useUser } from "@/store/backend/SysM/user";
import { cloneDeep } from "lodash";
import type { ElForm } from "element-plus";
import { useRoute } from "vue-router";
import BomTree from "./components/aside.vue";
import { useNavTabs } from "@/store/navTabs";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useBomProcess } from "@/store/backend/BomM/bomProcess";

const formRef = ref();
const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const navTabs = useNavTabs();
const dictionary = useDictionary();
const bomP = useBomProcess();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + sysMUser)
      ? (navTabs as any).pageSizeMap.get(route.path + sysMUser)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(sysMUser), //该用户管理增删改查封装好的api
  {
    pk: "userId",
    //table
    column: [
      /**
       * type为 操作按钮组类型
       * operator 通用搜索操作符,默认值为=,false禁用此字段通用搜索,支持的操作符见baTable.ts
       */
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("userName"),
        label: "用户名称",
        prop: "userName",
        align: "center",
        operatorPlaceholder: "模糊查询",
      },
      {
        show: filedShowOff("nickName"),
        label: "用户昵称",
        prop: "nickName",
        align: "center",
      },
      // {
      //   label: "性别",
      //   prop: "gender",
      //   align: "center",
      //   render: "tag",
      //   custom: { "0": "info", "1": "", "2": "success" },
      //   replaceValue: {
      //     "0": "未知",
      //     "1": "男",
      //     "2": "女",
      //   },
      // },
      // {
      //   show: filedShowOff("userType"),
      //   label: "用户类型",
      //   prop: "userType",
      //   align: "center",
      //   render: "tag",
      //   custom: { "0": "danger", "1": "success", "2": "info" },
      //   replaceValue: {
      //     "0": "系统用户",
      //     "1": "区域用户",
      //     "2": "企业用户",
      //   },
      //   operator: false,
      // },
      {
        show: filedShowOff("dept.deptName"),
        label: "部门",
        prop: "dept.deptName",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("phonenumber"),
        label: "联系方式",
        prop: "phonenumber",
        align: "center",
        operator: "LIKE",
        operatorPlaceholder: "模糊查询",
      },
      // {
      //   label: "最后登录ip",
      //   prop: "lastloginip",
      //   align: "center",
      //   operator: "LIKE",
      //   operatorPlaceholder: "模糊查询",
      //   render: "tag",
      // },
      // {
      //   label: "最后登录时间",
      //   prop: "lastlogintime",
      //   align: "center",
      //   render: "datetime",
      //   sortable: "custom",
      //   operator: "RANGE",
      //   width: 160,
      // },
      {
        show: filedShowOff("createTime"),
        label: "创建时间",
        prop: "createTime",
        align: "center",
        render: "datetime",
        sortable: "custom",
        // operator: "RANGE",
        width: 160,
        operator: false,
      },
      {
        show: filedShowOff("status"),
        label: "状态",
        prop: "status",
        align: "center",
        render: "switch",
        replaceValue: {
          "0": "正常",
          "1": "停用",
        },
      },
      {
        show: operatorShowOff([
          route.path + "/resetPwd",
          route.path + "/edit",
          route.path + "/remove",
        ]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            display: (row: TableRow, field: TableColumn) => {
              if (row.admin) {
                return false;
              }
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            display: (row: TableRow, field: TableColumn) => {
              if (row.admin) {
                return false;
              }
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "resetPwd",
            title: "重置密码",
            text: "",
            type: "primary",
            icon: "iconfont icon-yuechi",
            class: "table-row-edit",
            popconfirm: {
              confirmButtonText: "重置",
              cancelButtonText: "取消",
              confirmButtonType: "primary",
              title: "确定重置所选项吗",
            },
            disabledTip: false,
            display: (row: TableRow, field: TableColumn) => {
              if (row.admin) {
                return false;
              }
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
        operator: false,
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
  }, // 列数据
  {
    //默认表单数据 form
    defaultItems: {
      status: 0,
      password: "123456",
      companyid: 0, //用户不选择企业用户默认企业id为0
    },
  },
  //提交前
  {
    // 提交前
    onSubmit: (params: { formEl: InstanceType<typeof ElForm> }) => {
      //判断用户管理是新增还是编辑表单
      var items = cloneDeep(baTable.form.items!);

      //用户不选择区域用户默认区域id为0
      items.regions = formRef.value.getCheckeds()
        ? formRef.value.getCheckeds()
        : [0];
      for (const key in items) {
        if (items[key] === null) {
          delete items[key];
        }
      }

      // 表单验证通过后执行的api请求操作
      let submitCallback = () => {
        baTable.form.submitLoading = true;
        baTable.api
          .postData(baTable.form.operate!, items)
          .then((res) => {
            baTable.onTableHeaderAction("refresh", {});
            baTable.form.submitLoading = false;
            baTable.form.operateIds?.shift();
            if (baTable.form.operateIds!.length > 0) {
              baTable.toggleForm("edit", baTable.form.operateIds);
            } else {
              baTable.toggleForm();
            }
            baTable.runAfter("onSubmit", { res });
          })
          .catch((err) => {
            baTable.form.submitLoading = false;
          });
      };

      if (params.formEl) {
        baTable.form.ref = params.formEl;
        params.formEl.validate((valid) => {
          if (valid) {
            submitCallback();
          }
        });
      } else {
        submitCallback();
      }
      return false;
    },
  }
);
//初始化密码 用户修改密码后忘记密码联系管理员重置密码（固定密码）
const resetPwd = (name: string, row: anyObj) => {
  const User = useUser();
  //先获取用户详情
  baTable.api.edit(row.userId).then((res: any) => {
    res.data.postIds = res.postIds ? res.postIds : []; //编辑用户获取用户岗位信息
    res.data.roleIds = res.roleIds ? res.roleIds : []; //编辑用户获取用户角色信息
    res.data.regions = res.regions ? res.regions : []; //编辑用户获取用户区域信息
    res.data.companyid = res.companyid ? res.companyid : 0; //编辑用户获取用户企业信息
    res.data.password = "123456"; //后端有默认密码
    nextTick(() => {
      // 再初始化密码
      User.userResetPwd(res.data).then(() => {
        //刷新列表
        baTable.onTableHeaderAction("refresh", {});
      });
    });
  });
};

//获取字典
const getMenuStatus = () => {
  // if (
  //   JSON.stringify(dictionary.moreTags) == "{}" ||
  //   JSON.stringify(dictionary.moreTags["productType"])
  // ) {
  //   dictionary.getDictInfo("sys_plan_producttype").then((res: any) => {
  //     dictionary.moreTags["productType"] = getDictData(res);
  //     console.log("获取生产类型的字典", dictionary.moreTags);
  //   });
  // }
};

// getMenuStatus();

//接收工作中心树传递过来的数据
const filetrStation = (row: any, node: any) => {
  console.log("接收工作中心树传递过来的数据", row);

  if (node.checkedKeys.length == 0) {
    //表示取消选择直接调用刷新表单方法
    baTable.comSearch.form.deptId = "";
    baTable.onTableHeaderAction("refresh", {});
  } else {
    baTable.comSearch.form.deptId = row.id;
    baTable.getList(sysMUser);
  }
};

onMounted(() => {
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(sysMUser);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      console.log("data", data);
      if (data.name == "resetPwd") {
        resetPwd(data.name, data.row);
      }
    }
  );
});
// 获取数据，可以在页面的onMounted时执行，也可以比如先请求一个API，再执行获取数据
//baTable.getIndex()!.then(() => {
//查看请求完毕（已获取到表格数据）
//  baTable.initSort() // 初始化默认排序（如果需要）
//  baTable.dragSort() // 初始化拖拽排序（如果需要）
//})

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("bomP", bomP);
</script>
<style lang="scss" scoped>
// .default-main {
//   margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
// }
.default-main {
  margin: 0px !important;
}
</style>
